package com.shb.jutils.commons;

import java.lang.reflect.Field;

/**
 * 反射工具类
 * @author shb
 *
 */
public class ReflectUtil {

	private ReflectUtil(){}
	
	public static Object getProperty(String propertyName, Object obj){
		@SuppressWarnings("rawtypes")
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		Field.setAccessible(fields, true);
		for(int i =0; i < fields.length; i++){
			if(propertyName.equals(fields[i].getName())){
				try {
					return fields[i].get(obj);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return null;
	}
	
	public static void setProperty(String propertyName, Object obj, Object value){
		@SuppressWarnings("rawtypes")
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		Field.setAccessible(fields, true);
		for(int i =0; i < fields.length; i++){
			if(propertyName.equals(fields[i].getName())){
				try {
					fields[i].set(obj, value);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
	
	public static void setPropertyCoverSupper(String propertyName, Object obj, Object value){
		@SuppressWarnings("rawtypes")
		Class clazz = obj.getClass();
		Field[] fields;
		try {
			fields = clazz.getDeclaredFields();
			Field.setAccessible(fields, true);
			for(int i = 0; i< fields.length; i++){
				if(propertyName.equals(fields[i].getName())){
					fields[i].set(obj, value);
					return ;
				}
			}
			for(; clazz!= Object.class; clazz=clazz.getSuperclass()){
				try{
					Field field = clazz.getDeclaredField(propertyName);
					field.setAccessible(true);
					field.set(obj, value);
				}catch(NoSuchFieldException e){
					
				}
			}
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static Object getPropertyCoverSupper(String propertyName, Object obj){
		@SuppressWarnings("rawtypes")
		Class clazz = obj.getClass();
		Field[] fields;
		try {
			fields = clazz.getDeclaredFields();
			Field.setAccessible(fields, true);
			for(int i = 0; i < fields.length; i++){
				if(propertyName.equals(fields[i].getName())){
					return fields[i].get(obj);
				}
			}
			for(; clazz!= Object.class; clazz=clazz.getSuperclass()){
				try{
					Field field = clazz.getDeclaredField(propertyName);
					field.setAccessible(true);
					return field.get(obj);
				}catch(NoSuchFieldException e){
					
				}
			}
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		return null;
	}
}
